package com.liyueheng.app.dataWarehouseDetail.behavior

import com.liyueheng.util.{ConfigLoader, SaveAsTable, SparkConf}
import org.apache.spark.sql.functions._

object DailyPurchaseConversionRate {
  def analyze(): Unit = {
    println("------------------ 分析日购买转化率 -----------------")
    val spark = SparkConf.createSparkSession("DailyPurchaseRate")
    val dwd = ConfigLoader.getString("databases.dwd")
    val dws = ConfigLoader.getString("databases.dws")

    val df = spark.table(s"$dwd.user_act")

    val result = df.groupBy("act_date")
      .agg(
        sum(when(col("act_type") === 1, 1).otherwise(0)).alias("pv"),
        sum(when(col("act_type") === 2, 1).otherwise(0)).alias("buy"),
        sum(when(col("act_type") === 3, 1).otherwise(0)).alias("fav"),
        sum(when(col("act_type") === 4, 1).otherwise(0)).alias("comment"),
        sum(when(col("act_type") === 5, 1).otherwise(0)).alias("cart"),
        (countDistinct(when(col("act_type") === 2, col("user"))) / countDistinct(col("user")))
          .alias("buy_rate")
      )
      .orderBy("act_date")

    SaveAsTable.saveAsTable(result, s"$dws.detail_daily_buy_rate")
    SparkConf.stopSparkSession(spark)
  }
}
